package com.gesaracino.googlemapsgateway;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView forwardingInProgressTV;
	private TextView noActionToPerformTV;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		forwardingInProgressTV = (TextView) findViewById(R.id.forwarding_in_progress);
		noActionToPerformTV = (TextView) findViewById(R.id.no_action_to_perform);
	}

	@Override
	protected void onStart() {
		super.onStart();

		final Intent intent = getIntent();

		if (intent == null || intent.getDataString() == null || intent.getDataString().length() == 0) {
			noActionToPerformTV.setVisibility(View.VISIBLE);
			return;
		}

		forwardingInProgressTV.setVisibility(View.VISIBLE);

		final String[] fields = intent.getDataString().split("/");
		final String contactId = fields[fields.length - 1];

		final String[] projection = new String[] {
				ContactsContract.CommonDataKinds.StructuredPostal._ID,
				ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS };
		final String selection = ContactsContract.CommonDataKinds.StructuredPostal._ID + "=?";
		final String[] selectionArgs = new String[] { contactId };
		final Cursor c = getContentResolver().query(
				ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
				projection, selection, selectionArgs, null);

		if (c == null || c.getCount() == 0 || c.getCount() > 1) {
			noActionToPerformTV.setVisibility(View.VISIBLE);
			forwardingInProgressTV.setVisibility(View.GONE);
			return;
		}

		final int idColumnIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal._ID);
		c.moveToFirst();
		final String currentId = c.getString(idColumnIndex);

		if (!currentId.equals(contactId)) {
			noActionToPerformTV.setVisibility(View.VISIBLE);
			forwardingInProgressTV.setVisibility(View.GONE);
			return;
		}

		final int formattedAddressColumnIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
		final String formattedAddress = c.getString(formattedAddressColumnIndex);

		final String openInMapsUri = String.format("geo:0,0?q=%s", formattedAddress);
		final Intent openInMapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(openInMapsUri));
		startActivity(openInMapsIntent);
	}

	@Override
	protected void onStop() {
		super.onStop();
		noActionToPerformTV.setVisibility(View.GONE);
		forwardingInProgressTV.setVisibility(View.GONE);
	}
}
